package com.jboost.modules.app.util;

import com.google.common.collect.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

public class RequestUtil {

    /**
     * 对uri中可能出现的多个斜杠去重
     *
     * @param request
     * @return
     */
    public static String trimURI(HttpServletRequest request) {
        String uri = request.getRequestURI();
        StringBuffer sb = new StringBuffer();
        boolean flag = false;
        for (int i = 0; i < uri.length(); i++) {
            char c = uri.charAt(i);
            if (c == '/') {
                if (flag) {
                    continue;
                }
                flag = true;
            } else {
                flag = false;
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 获取ip地址
     *
     * @param request
     * @return
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = null;
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 获取request中所有参数
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllParameter(HttpServletRequest request) {
        Map<String, String> map = Maps.newHashMap();
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = enu.nextElement();
            String value = request.getParameter(paraName);
            if (value != null) {
                try {
                    value = URLDecoder.decode(value, StandardCharsets.UTF_8.name());
                } catch (UnsupportedEncodingException e) {
                }
            }
            map.put(paraName, value);
        }
        return map;
    }

    public static String httpPost(String url, Map<String, String> params) throws IOException {
        String responseJson = "";
        //整理参数的字符编码
        List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            String value = params.get(key);
            nameValues.add(new BasicNameValuePair(key, value));
        }
        Long dt = System.currentTimeMillis() / 1000;
        params.put("_timestamp_", dt + "");
        params.put("v", "1.0");
        String value = Hmacer.signRequest("@&*Ytq1SR4DnTLy*rt6xdbVksOMql0J8H#9RP%fcmg4OHWYBwif6EW9i@hWx6PXatBfGWB936^otrPPnBkxyTy8#eIycfqfJ4VmM", params);
        nameValues.add(new BasicNameValuePair("_timestamp_", "" + dt));
        nameValues.add(new BasicNameValuePair("v", "1.0"));
        nameValues.add(new BasicNameValuePair("_signature_", value));

        HttpPost httpRequest = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(90000).setConnectTimeout(90000).build();// 设置请求和传输超时时间
        httpRequest.setConfig(requestConfig);

        HttpEntity httpEntity = new UrlEncodedFormEntity(nameValues, "UTF-8");
        httpRequest.setEntity(httpEntity);
        return request(httpRequest);
    }

    private static String request(HttpUriRequest request) throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(request);
        String result = EntityUtils.toString(response.getEntity());
        response.close();
        httpClient.close();
        return result;
    }

}
